<?php
namespace app\index\behavior;

use Firebase\JWT\JWT;
use think\facade\Request;
use think\facade\Session;

class Test
{
    public function actionBegin()
    {
        $req = Request::instance();
        $contr = $req->controller();
        if ('Login'==$contr){
            return;
        }
        if ('Index'==$contr){
            return;
        }
        if ('Register'==$contr){
            return;
        }
        $act = $req->action();
        $url = strtolower("/$contr/$act");
//        @$token = $_SERVER['HTTP_X_TOKEN'];
        $token = Session::get("token");
       try{
           if (empty($token)){
               throw new \Exception("尚未登录");
           }
           $urls = JWT::decode($token, config('jwt_key'),['HS256']);
           if (!in_array($url,$urls)){
               throw new \Exception("不具备权限");
//               print_r($urls);
//               print_r($url);
           }
       }catch (\Exception $e){
           if ($e instanceof UnexpectedValueException ||$e instanceof SignatureInvalidException){
               $message = 'token失效';
           }elseif($e instanceof ExpiredException){
               $message = '登录超时';
           }else{
               $message = $e->getMessage();
           }
           header('Content-Type:text/plain','charset=UTF-8');
           echo $message;
         die;
       }
//        echo $token.$url."哈哈";
//        print_r($urls);
//        print_r($url);

    }

}
